package com.rf.richfitwheel.admin.sys.service.impl;


import com.rf.richfitwheel.admin.sys.dao.*;
import com.rf.richfitwheel.admin.sys.model.*;
import com.rf.richfitwheel.admin.sys.service.SysUserRoleService;
import com.rf.richfitwheel.admin.sys.vo.UserVO;
import com.rf.richfitwheel.admin.utils.MapCaseUtil;
import com.rf.richfitwheel.admin.utils.UserUtil;
import com.rf.richfitwheel.common.exception.BusinessException;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rf.richfitwheel.admin.sys.service.SysMenuService;
import com.rf.richfitwheel.admin.sys.service.SysRoleMenuService;
import com.rf.richfitwheel.common.contants.Constant;
import com.rf.richfitwheel.common.utils.StringUtils;
import com.rf.richfitwheel.common.utils.TreeUtils;
import com.rf.richfitwheel.common.utils.UuidUtil;

import java.util.*;
import java.util.stream.Collectors;


@Service("sysMenuService")
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private MenuBeanMapper menuBeanMapper;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SqlAdapterMapper sqlAdapterMapper;//注入dao
    @Autowired
    private SysCommUseMenuMapper sysCommUseMenuMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private SysMenuClickLogMapper sysMenuClickLogMapper;

    @Autowired
    private SysUserRoleService sysUserRoleService;
    /**
     * 查询父菜单id列表
     *
     * @param parentId   父菜单ID
     * @param menuIdList 用户菜单ID
     * @return 菜单列表
     */
    @Override
    public List<MenuBean> queryListParentId(String parentId, List<String> menuIdList) {
        List<MenuBean> menuList = queryListParentId(parentId);
        if (menuIdList == null) {
            return menuList;
        }

        List<MenuBean> userMenuList = new ArrayList<>();
        for (MenuBean menu : menuList) {
            if (menuIdList.contains(menu.getId())) {
                userMenuList.add(menu);
            }
        }
        return userMenuList;
    }

    @Override
    public List<MenuBean> queryListParentId(String parentId) {
        return menuBeanMapper.queryListParentId(parentId);
    }

    @Override
    public List<MenuBean> queryNotButtonList() {
        return menuBeanMapper.queryNotButtonList(2);
    }

    @Override
    public List<MenuBean> getUserMenuList(String userId) {
        //系统管理员，拥有最高权限
		/*if( Constant.SUPER_ADMIN.equals(userId)){
			return getAllMenuList(null);
		}*/
        //用户菜单列表，角色权限，系统内置，避免系统管理员权限被删除
        String sqlRole = "select rm.menu_id from sys_user_role ur, sys_role_menu rm, sys_user u,sys_menu m where ur.role_id=rm.role_id and u.id=ur.user_id and rm.menu_id=m.id and u.id='" + userId + "' and m.terminal='" + Constant.TerminalType.TERMINALTYPE_PC.getValue() + "'";
        List<Map<String, Object>> list2 = MapCaseUtil.mapKeyToLowerCase(sqlAdapterMapper.selectSQL(sqlRole));

        List<String> menuIdList = new ArrayList<>();
        for (Map<String, Object> map : list2) {
            menuIdList.add(map.get("menu_id").toString());
        }

        return getAllMenuList(menuIdList);
//		return new ArrayList<MenuBean>();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "menus", key = "'menulistTree'")
    public void delete(String menuId) {
        //删除菜单
        menuMapper.deleteByPrimaryKey(menuId);
        //删除菜单与角色关联
//		sysRoleMenuService.deleteByMap(new MapUtils().put("menu_id", menuId));
    }

    /**
     * 获取所有菜单列表
     */
    private List<MenuBean> getAllMenuList(List<String> menuIdList) {
        //查询根菜单列表
        List<MenuBean> menuList = queryListParentId("0", menuIdList);
        //递归获取子菜单
        getMenuTreeList(menuList, menuIdList);

        return menuList;
    }

    /**
     * 递归
     */
    private List<MenuBean> getMenuTreeList(List<MenuBean> menuList, List<String> menuIdList) {
        List<MenuBean> subMenuList = new ArrayList<>();

        for (MenuBean entity : menuList) {
            //目录
            if (entity.getType() == Constant.MenuType.CATALOG.getValue()) {
                entity.setList(getMenuTreeList(queryListParentId(entity.getId(), menuIdList), menuIdList));
            }
            subMenuList.add(entity);
        }

        return subMenuList;
    }

    @Override
    public List<Menu> selectList(JSONObject object) {
        MenuExample example = new MenuExample();
        MenuExample.Criteria criteria = example.createCriteria();
        example.setOrderByClause(" order_num ");
        if (object.containsKey("terminal")) {
            String objTerminal = object.get("terminal") == null ? "" : object.get("terminal").toString();
            if (StringUtils.isNotBlank(objTerminal)) {
                criteria.andTerminalIn(Arrays.asList(objTerminal.split(",")));
            }
        }
        if (object.containsKey("moduleType")) {
            String objModuleType = object.get("moduleType") == null ? "" : object.get("moduleType").toString();
            if (StringUtils.isNotBlank(objModuleType)) {
                criteria.andModuleTypeIn(Arrays.asList(objModuleType.split(",")));
            }
        }
        /*FileWriter writer = null;
		try {
			writer = new FileWriter("C:\\Users\\Administrator\\Desktop\\menu.txt", true);   
			for(Menu menu : list) {
				if(1 == menu.getType()) {
					String url = menu.getUrl();
					System.out.println("{ path: '"+url.replaceAll("/", "-")+"', component: () => import('@/views/modules/"+url+".vue'), name: '"+url.replaceAll("/", "-")+"', meta: {menuId:'"+menu.getId()+"', title: '"+menu.getName()+"', isDynamic: true, isTab: true,iframeUrl: '' } },");
			         writer.write("{ path: '"+url.replaceAll("/", "-")+"', component: () => import('@/views/modules/"+url+".vue'), name: '"+url.replaceAll("/", "-")+"', meta: {menuId:'"+menu.getId()+"', title: '"+menu.getName()+"', isDynamic: true, isTab: true,iframeUrl: '' } },"+System.getProperty("line.separator"));     
				}
			}
		} catch (IOException e) {
			try {
				writer.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}*/
        return menuMapper.selectByExample(example);
    }

    @Override
    public Menu selectById(String parentId) {
        return menuMapper.selectByPrimaryKey(parentId);
    }

    @Override
    @CacheEvict(value = "menus", key = "'menulistTree'")
    @Transactional(rollbackFor = Exception.class)
    public void insert(Menu menu) {
        menu.setId(UuidUtil.get32UUID());
        if (StringUtils.isBlank(menu.getSysResource())) {
            menu.setSysResource("1");
        }
        menuMapper.insert(menu);
    }

    @Override
    @CacheEvict(value = "menus", key = "'menulistTree'")
    @Transactional(rollbackFor = Exception.class)
    public void updateById(Menu menu) {
        menuMapper.updateByPrimaryKey(menu);
    }

    @Override
    @Cacheable(value = "menus", key = "'menulistTree'")
    public List<TreeUtils> gerResTree() throws Exception {
        MenuExample example = new MenuExample();
        example.setOrderByClause(" order_num ");
        List<Menu> list = menuMapper.selectByExample(example);
        return TreeUtils.getTreeList(list, "id", "parentId", "name", null, null);
    }

    @Override
    public Set<String> getUserPermissions(String id) {
        Set<String> permsSet = new HashSet<>();
        String sql = "select m.perms from sys_menu m, t_station_user su,t_station_resource sr where m.id = sr.resource_id and sr.station_id = su.station_id and (m.type = 2 or (m.type=1 and m.perms is not null)) and su.user_id = '" + id + "'";
        List<Map<String, Object>> list = MapCaseUtil.mapKeyToLowerCase(sqlAdapterMapper.selectSQL(sql));
        String sqlAccSub = "select m.perms from sys_menu m, t_accmngsub_role_user su,t_accmngsub_role_menu sr where m.id = sr.res_id and sr.role_id = su.role_id and (m.type = 2 or (m.type=1 and m.perms is not null)) and su.user_id ='" + id + "'";
        List<Map<String, Object>> list1 = MapCaseUtil.mapKeyToLowerCase(sqlAdapterMapper.selectSQL(sqlAccSub));
        String sqlRole = "select m.perms from sys_menu m, sys_user_role su,sys_role_menu sr where m.id = sr.menu_id and sr.role_id = su.role_id and (m.type = 2 or (m.type=1 and m.perms is not null)) and su.user_id ='" + id + "'";
        List<Map<String, Object>> list2 = MapCaseUtil.mapKeyToLowerCase(sqlAdapterMapper.selectSQL(sqlRole));
        for (Map map : list) {
            if (StringUtils.isBlank(map.get("perms"))) {
                continue;
            }
            permsSet.addAll(Arrays.asList(map.get("perms").toString().trim().split(",")));
        }
        for (Map map : list1) {
            if (StringUtils.isBlank(map.get("perms"))) {
                continue;
            }
            permsSet.addAll(Arrays.asList(map.get("perms").toString().trim().split(",")));
        }
        for (Map map : list2) {
            if (StringUtils.isBlank(map.get("perms"))) {
                continue;
            }
            permsSet.addAll(Arrays.asList(map.get("perms").toString().trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public List<MenuBean> getUserMenuListTopLevel(String userId) {
		/*String sql = "select distinct sr.resource_id from t_station_user su,t_station_resource sr,sys_user u where su.station_id=sr.station_id and u.id=su.user_id and u.id='" + userId + "'";
		//用户菜单列表
		List<Map<String, Object>> list = sqlAdapterMapper.selectSQL(sql);
		List<String> menuIdList = new ArrayList<String>();
		for(Map<String, Object> map : list) {
			menuIdList.add(map.get("resource_id").toString());
		}*/
        return menuBeanMapper.queryListParentIdLimit(userId);
    }

    @Override
    public List<MenuBean> getCommUseMenuTree(String userId) {
		/*String sql = "select distinct sr.resource_id from t_station_user su,t_station_resource sr,sys_user u,sys_comm_use_menu um where su.station_id=sr.station_id and u.id=su.user_id and u.id=um.user_id and sr.resource_id=um.res_id and u.id='" + userId + "'";
		//用户菜单列表
		List<Map<String, Object>> list = sqlAdapterMapper.selectSQL(sql);
		List<String> menuIdList = new ArrayList<String>();
		for(Map<String, Object> map : list) {
			menuIdList.add(map.get("resource_id").toString());
		}
		return getAllMenuList(menuIdList);*/
        return menuBeanMapper.queryCommUseMenuList(userId);
    }

    /**
     * 导航菜单,常用菜单，已选择的菜单
     *
     * @param userId 用户id
     * @param terminal 终端
     * @return 常用菜单
     */
    @Override
    public List<MenuBean> getCommUseMenuTree(String userId, String terminal) {
        /*if (Constant.TerminalType.TERMINALTYPE_PC.getValue().equals(terminal)) {

        } else if (Constant.TerminalType.TERMINALTYPE_APP.getValue().equals(terminal)) {

        }*/
        return null;
    }

    @Override
    public List<Map<String, Object>> getCommUseMenuSetTree(String userId) {
        String sql = "select distinct m.*,case m.type when '1' then 'false' else 'true' end as disabled from sys_menu m, sys_user_station su,sys_station_menu sr,sys_user u where m.id=sr.menu_id and su.station_id=sr.station_id and u.id=su.user_id and m.type<>" + Constant.MenuType.BUTTON.getValue() + " and u.id='" + userId + "' order by m.order_num";
        return MapCaseUtil.mapKeyToLowerCase(sqlAdapterMapper.selectSQL(sql));
    }

    @Override
    public List<Map<String, Object>> getCommUseMenuSetTree(String userId, String terminal) {
        if (Constant.TerminalType.TERMINALTYPE_PC.getValue().equals(terminal)) {
            String sql = "select distinct m.*,case m.type when '1' then 'false' else 'true' end as disabled from sys_menu m, sys_user_station su,sys_station_menu sr,sys_user u where m.id=sr.menu_id and su.station_id=sr.station_id and u.id=su.user_id and m.type<>" + Constant.MenuType.BUTTON.getValue() + "  and m.terminal='" + terminal + "' and u.id='" + userId + "' order by m.order_num";
            String sql1 = "select DISTINCT m.*, CASE m.type WHEN '1' THEN 'false' ELSE 'true' END AS disabled from sys_menu m, sys_role_menu rm, sys_user_role ru, sys_user u where m.id=rm.menu_id and ru.role_id=rm.role_id and u.id=ru.user_id and m.type <> " + Constant.MenuType.BUTTON.getValue() + " and m.terminal = '" + terminal + "' and u.id='" + userId + "' order by m.order_num";
            List<Map<String, Object>> list = sqlAdapterMapper.selectSQL(sql);
            list.addAll(sqlAdapterMapper.selectSQL(sql1));
            //字段转小写，兼容oracle等数据库，机智的一P
            return MapCaseUtil.mapKeyToLowerCase(list);
        } else {
            return null;
        }
    }

    /**
     * 查询已设置的常用菜单
     *
     * @param id 用户id
     * @param terminal 终端
     * @return 常用菜单
     */
    @Override
    public List<MenuBean> getMenuCheckList(String id, String terminal) {
        return menuBeanMapper.getMenuCheckList(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveCommUseMenu(String[] ids, UserVO userVO) {
        SysCommUseMenuExample example = new SysCommUseMenuExample();
        SysCommUseMenuExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userVO.getId());
        sysCommUseMenuMapper.deleteByExample(example);
        for (String id : ids) {
            SysCommUseMenu sysCommUseMenu = new SysCommUseMenu();
            sysCommUseMenu.setId(UuidUtil.get32UUID());
            sysCommUseMenu.setResId(id);
            sysCommUseMenu.setUserId(userVO.getId());
            sysCommUseMenuMapper.insert(sysCommUseMenu);
        }
    }

    @Override
    public void menuClick(String menuId, UserVO userVO) throws Exception {
        SysMenuClickLog clickLog = new SysMenuClickLog();
        clickLog.setMenuId(menuId);
        clickLog.setUserId(userVO.getId());
        clickLog.setOperTime(new Date());
        sysMenuClickLogMapper.insert(clickLog);
    }

    /* （非 Javadoc）
     * gerResTreeByTerminal
     * @param terminals
     * @param user
     * @return
     * @throws Exception
     * @see com.rf.richfitwheel.admin.sys.service.SysMenuService#gerResTreeByTerminal(java.util.List)
     */
    @Override
    public List<TreeUtils> gerResTreeByTerminal(List<String> terminals, UserVO userVO) throws Exception {
        MenuExample example = new MenuExample();
        MenuExample.Criteria criteria = example.createCriteria();
//        if (!userVO.getTenantId().equals(Constant.SUPER_ADMIN_TENANTID)) {
////			paramsNew.put("tenantId", user.getTenantId());
//            criteria.andTenantIdEqualTo(userVO.getTenantId());
//        }
        Map<String, Object> map = new HashMap<>();
        //超级管理员角色只能由超级管理员维护
        List<UserRole> listUser = sysUserRoleService.getListByUserId(userVO.getId());
        for(UserRole ur : listUser){
            map.put(ur.getRoleId(), ur);
        }
        if(!map.containsKey("1")){
            //不是超级管理员不能操作菜单管理和数据字典
            criteria.andTenantIdNotEqualTo("2");
        }
        example.setOrderByClause(" order_num ");
        List<Menu> list = menuMapper.selectByExample(example);
        List<TreeUtils> treeList = TreeUtils.getTreeList(list, "id", "parentId", "name", null, null);
        return treeList;
    }

    /* （非 Javadoc）
     * getUserMenuList
     * @param id
     * @param terminals  1:pc 2:app
     * @return
     * @see com.rf.richfitwheel.admin.sys.service.SysMenuService#getUserMenuList(java.lang.String, java.lang.String)
     */
    @Override
    public List<MenuBean> getUserMenuList(String id, String terminal, String sessionId) {
        //系统管理员，拥有最高权限
		/*if( Constant.SUPER_ADMIN.equals(userId)){
			return getAllMenuList(null);
		}*/
        //
        UserVO userVO = UserUtil.getUser();
        if (userVO.getDefaultOrg() == null || StringUtils.isBlank(userVO.getDefaultOrg().getId())) {
            throw new BusinessException("没有为该用户设置默认管理机构");
        }
        List<String> menuIdList = new ArrayList<>();
        if (Constant.TerminalType.TERMINALTYPE_PC.getValue().equals(terminal)) {
            //用户菜单列表，角色权限，系统内置，避免系统管理员权限被删除
//			String sqlRole = "select rm.menu_id from sys_user_role ur, sys_role_menu rm, sys_user u,sys_menu m where ur.role_id=rm.role_id and u.id=ur.user_id and rm.menu_id=m.id and u.id='" + id + "' and m.terminal='" + Constant.TerminalType.TERMINALTYPE_PC.getValue() +"'" ;

            String sqlRole = "SELECT rm.menu_id FROM sys_user_role ur, sys_role_menu rm WHERE ur.role_id = rm.role_id AND ur.user_id ='" + userVO.getId() + "' and ur.org_id='" + userVO.getDefaultOrg().getId() + "'";

            List<Map<String, Object>> list2 = MapCaseUtil.mapKeyToLowerCase(sqlAdapterMapper.selectSQL(sqlRole));
            for (Map<String, Object> map : list2) {
//				menuIdList.add(map.get("menu_id").toString());
//				MenuBean menuBean = menuBeanMapper.getMenuByMenuId(map.get("menu_id").toString());
//				list.add(menuBean);
                if (!menuIdList.contains(map)) {
                    menuIdList.add(map.get("menu_id") == null ? map.get("MENU_ID").toString() : map.get("menu_id").toString());
                }
            }
        } else {

        }
//		return list;
        return getAllMenuList(menuIdList, sessionId);
    }

    /* （非 Javadoc）
     * getUserPermissions
     * @param id
     * @param terminals
     * @return
     * @see com.rf.richfitwheel.admin.sys.service.SysMenuService#getUserPermissions(java.lang.String, java.lang.String)
     */
    @Override
    public Set<String> getUserPermissions(String id, String terminal) {
        Set<String> permsSet = new HashSet<>();
        String sqlRole = "select m.perms from sys_menu m, sys_user_role su,sys_role_menu sr where m.id = sr.menu_id and sr.role_id = su.role_id and (m.type = " + Constant.MenuType.BUTTON.getValue() + " or (m.type=" + Constant.MenuType.MENU.getValue() + " and m.perms is not null)) and su.user_id ='" + id + "'";
        List<Map<String, Object>> list2 = MapCaseUtil.mapKeyToLowerCase(sqlAdapterMapper.selectSQL(sqlRole));
        for (Map map : list2) {
            if (StringUtils.isBlank(map.get("perms") == null ? map.get("PERMS") : map.get("perms"))) {
                continue;
            }
            permsSet.addAll(Arrays.asList(map.get("perms") == null ? map.get("PERMS").toString().trim().split(",") : map.get("perms").toString().trim().split(",")));
        }
        return permsSet;
    }

    /* （非 Javadoc）
     * getCommUseMenuTreeByTerminal
     * @param id
     * @param terminal
     * @return
     * @see com.rf.richfitwheel.admin.sys.service.SysMenuService#getCommUseMenuTreeByTerminal(java.lang.String, java.lang.String)
     */
    @Override
    public List<MenuBean> getCommUseMenuTreeByTerminal(String id, String[] terminals) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", id);
        map.put("terminals", Arrays.asList(terminals));
        return menuBeanMapper.queryCommUseMenuListByTerminal(map);
    }

    /* （非 Javadoc）
     * getUserMenuList
     * @param id
     * @param sessionId
     * @return
     * @see com.rf.richfitwheel.admin.sys.service.SysMenuService#getUserMenuList(java.lang.String, java.lang.String)
     */
    @Override
    public List<MenuBean> getUserMenuList(String userId, String sessionId) {
        //系统管理员，拥有最高权限
		/*if( Constant.SUPER_ADMIN.equals(userId)){
			return getAllMenuList(null);
		}*/
        //用户菜单列表，角色权限，系统内置，避免系统管理员权限被删除
        String sqlRole = "select rm.menu_id from sys_user_role ur, sys_role_menu rm, sys_user u,sys_menu m where ur.role_id=rm.role_id and u.id=ur.user_id and rm.menu_id=m.id and u.id='" + userId + "' and m.terminal='" + Constant.TerminalType.TERMINALTYPE_PC.getValue() + "'";
        List<Map<String, Object>> list2 = MapCaseUtil.mapKeyToLowerCase(sqlAdapterMapper.selectSQL(sqlRole));

        List<String> menuIdList = new ArrayList<>();
        for (Map<String, Object> map : list2) {
            menuIdList.add(map.get("menu_id") == null ? map.get("MENU_ID").toString() : map.get("menu_id").toString());
        }

        return getAllMenuList(menuIdList, sessionId);
    }


    /**
     * 根据菜单终端类型获取菜单树,增加一个顶级节点
     *
     * @param tList 根据菜单终端类型获取菜单树,增加一个顶级节点
     * @return 根据菜单终端类型获取菜单树,增加一个顶级节点
     */
    @Override
    public List<TreeUtils> getResByTerminalDisableParent(List<String> tList) throws Exception {
        MenuExample example = new MenuExample();
        MenuExample.Criteria criteria = example.createCriteria();
        criteria.andTerminalIn(tList);
        example.setOrderByClause(" order_num ");
        List<Menu> list = menuMapper.selectByExample(example);
        List<TreeUtils> treeList = TreeUtils.getTreeList(list, "id", "parentId", "name", null, null);
        //递归禁用有子节点的数据
        //disableParent(treeList);
        //增加一个顶级节点
        List<TreeUtils> returnList = new ArrayList<>();
        TreeUtils top = new TreeUtils();
        top.setId("0");
        top.setName("全部");
        top.setDisabled(false);
        top.setChildList(treeList);
        returnList.add(top);
        return returnList;
    }

    @Override
    public List<MenuBean> queryByModuleNotButtonList(String moduleType) {
        MenuBean menuBean = new MenuBean();
        menuBean.setType(2);
        menuBean.setModuleType(moduleType);
        return menuBeanMapper.queryByModuleNotButtonList(menuBean);
    }

    @Override
    public List<TreeUtils> gerResTreeByModuleType(UserVO userVO, String moduleType) throws Exception {
        MenuExample example = new MenuExample();
        MenuExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(moduleType)) {
//			paramsNew.put("tenantId", user.getTenantId());
            criteria.andModuleTypeEqualTo(moduleType);
        } else {
            criteria.andModuleTypeEqualTo("");
        }
        Map<String, Object> map = new HashMap<>();
        //超级管理员角色只能由超级管理员维护
        List<UserRole> listUser = sysUserRoleService.getListByUserId(userVO.getId());
        for(UserRole ur : listUser){
            map.put(ur.getRoleId(), ur);
        }
        if(!map.containsKey("1")){
            //不是超级管理员不能操作菜单管理和数据字典
            criteria.andTenantIdNotEqualTo("2");
        }
        example.setOrderByClause(" order_num ");
        List<Menu> list = menuMapper.selectByExample(example);
        return TreeUtils.getTreeList(list, "id", "parentId", "name", null, null);
    }

    @Override
    public List<MenuBean> getUserAllMenuList(String id, String terminal, String sessionId) {
        UserVO user = UserUtil.getUser();
        List<String> menuIdList = new ArrayList<>();
        List<OrgVO> mngOrgs = user.getMngOrgs();
        if (mngOrgs.isEmpty()) {
            throw new BusinessException("没有为该用户设置管理机构");
        }
        for (OrgVO orgVO : mngOrgs) {
            if (Constant.TerminalType.TERMINALTYPE_PC.getValue().equals(terminal)) {
                String sqlRole = "SELECT rm.menu_id FROM sys_user_role ur, sys_role_menu rm WHERE ur.role_id = rm.role_id AND ur.user_id ='" + user.getId() + "' and ur.org_id='" + orgVO.getId() + "'";
                List<Map<String, Object>> list2 = MapCaseUtil.mapKeyToLowerCase(sqlAdapterMapper.selectSQL(sqlRole));
                for (Map<String, Object> map_ : list2) {
                    if (!menuIdList.contains(map_)) {
                        //数据库兼容oracle、达梦等字段名是大写
                        menuIdList.add(map_.get("menu_id") == null ? map_.get("MENU_ID").toString() : map_.get("menu_id").toString());
                    }
                }
            } else {

            }
        }
        return getAllMenuList(menuIdList, sessionId);


    }

    /**
     * 获取用户有权限的模块
     *
     * @param user 用户
     * @return 模块
     */
    @Override
    public List<Map<String, Object>> getUserModulesPermissions(UserVO user) {
        String sqlModule = "SELECT m.module_type,dic.data_name FROM sys_menu m, sys_dictionary  dic, sys_user_role ur, sys_role_menu rm WHERE dic.class_code='MODULE' and m.module_type=dic.data_code and m.id=rm.menu_id and ur.role_id = rm.role_id AND ur.user_id ='" + user.getId() + "' and ur.org_id='" + user.getDefaultOrg().getId() + "' GROUP BY m.module_type,dic.data_name";
        return MapCaseUtil.mapKeyToLowerCase(sqlAdapterMapper.selectSQL(sqlModule));
    }

    /**
     * 根据终端和模块获取当前登陆用户的导航菜单
     *
     * @param id        用户id
     * @param terminal  终端 {@code com.rf.richfitwheel.common.contants.Constant.TerminalType}
     * @param module    模块 {@code com.rf.richfitwheel.common.contants.Constant.SystemModule}
     * @param sessionId 会话id
     * @return 导航菜单
     */
    @Override
    public List<MenuBean> getUserMenuList(String id, String terminal, String module, String sessionId) {
        UserVO userVO = UserUtil.getUser();
        if (userVO.getDefaultOrg() == null || StringUtils.isBlank(userVO.getDefaultOrg().getId())) {
            throw new BusinessException("没有为该用户设置默认管理机构");
        }
        List<String> menuIdList = new ArrayList<>();
        Map<String, Object> param = new HashMap<>();
        if (Constant.TerminalType.TERMINALTYPE_PC.getValue().equals(terminal)) {
            param.put("userId", userVO.getId());
            param.put("orgId", userVO.getDefaultOrg() == null ? "" : userVO.getDefaultOrg().getId());
            List<String> modules = Arrays.stream(module.split(",")).collect(Collectors.toList());
            String sysModule = Constant.SystemModule.sys.name();
            modules.add(sysModule);
            param.put("modules", modules);
            List<Map<String, Object>> authMenus = roleMenuMapper.getAuthMenusByUserAndModules(param);
//            String sqlRole = "SELECT rm.menu_id FROM sys_user_role ur, sys_role_menu rm, sys_menu m WHERE ur.role_id = rm.role_id AND rm.menu_id=m.id AND ur.user_id ='" + userVO.getId() + "' and ur.org_id='" + userVO.getDefaultOrg().getId() + "' and m.module_type in ('" + Constant.SystemModule.sys +"','" + module +"')";

            List<Map<String, Object>> list2 = MapCaseUtil.mapKeyToLowerCase(authMenus);
            for (Map<String, Object> map : list2) {
                if (!menuIdList.contains(map)) {
                    menuIdList.add(map.get("menu_id") == null ? map.get("MENU_ID").toString() : map.get("menu_id").toString());
                }
            }
        } else {

        }
        return getAllMenuList(menuIdList, sessionId);
    }

    /**
     * 递归禁用有子节点的数据
     *
     * @param treeList 菜单
     */
    private void disableParent(List<TreeUtils> treeList) {
        for (TreeUtils treeData : treeList) {
            if (treeData.getChildList() != null && !treeData.getChildList().isEmpty()) {
                treeData.setDisabled(true);
                disableParent(treeData.getChildList());
            } else {
                treeData.setDisabled(false);
            }
        }
    }

    /**
     * 获取所有菜单列表
     *
     * @param menuIdList 菜单
     * @param sessionId 会话id
     * @return 所有菜单列表
     */
    private List<MenuBean> getAllMenuList(List<String> menuIdList, String sessionId) {
        //查询根菜单列表
        List<MenuBean> menuList = queryListParentId("0", menuIdList);
        //递归获取子菜单
        getMenuTreeList(menuList, menuIdList, sessionId);

        return menuList;
    }

    /**
     * 递归,系统外资源拼接sessionId
     *
     * @param menuList 菜单
     * @param menuIdList 菜单
     * @param sessionId 会话id
     */
    private List<MenuBean> getMenuTreeList(List<MenuBean> menuList, List<String> menuIdList, String sessionId) {
        List<MenuBean> subMenuList = new ArrayList<>();

        for (MenuBean menuBean : menuList) {
            //目录
            if (menuBean.getType() == Constant.MenuType.CATALOG.getValue()) {
                List<MenuBean> menuBeans = queryListParentId(menuBean.getId(), menuIdList);
                List<MenuBean> menuTreeList = getMenuTreeList(menuBeans, menuIdList, sessionId);
                menuBean.setList(menuTreeList);
//				entity.setList(getMenuTreeList(queryListParentId(entity.getId(), menuIdList), menuIdList, sessionId));
            }
//			if("0".equals(entity.getSysResource())) {
//				entity.setUrl(entity.getUrl().indexOf("?") < 0 ? entity.getUrl() + "?ANNUITY-JSESSIONID=" + sessionId : entity.getUrl() + "&ANNUITY-JSESSIONID=" + sessionId);
//			}
            subMenuList.add(menuBean);
        }

        return subMenuList;
    }

    /**
     * 递归处理菜单路径
     *
     * @param pid 上级id
     * @param menuName 菜单名
     * @return 菜单路径
     */
    private String dealMenuName(String pid, String menuName) {
        String sql = "select name,parent_id from sys_menu m where id='" + pid + "'";
        List<Map<String, Object>> list = MapCaseUtil.mapKeyToLowerCase(sqlAdapterMapper.selectSQL(sql));
        if (!list.isEmpty()) {
            menuName = list.get(0).get("name") == null ? "" : list.get(0).get("name").toString() + "/" + menuName;
            if (list.get(0).get("parent_id") != null && !"0".equals(list.get(0).get("parent_id").toString())) {
                menuName = dealMenuName(list.get(0).get("parent_id").toString(), menuName);
            }
        }
        return menuName;
    }

}
